package com.itzxx.huazhun.ui.splash

import android.annotation.SuppressLint
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.View
import android.view.WindowInsets
import androidx.lifecycle.lifecycleScope
import com.itzxx.huazhun.databinding.ActivitySplashBinding
import com.itzxx.huazhun.ui.login.LoginActivity
import com.itzxx.library_base_ktx.base.activity.BaseVmDbActivity
import kotlinx.coroutines.*


class SplashActivity : BaseVmDbActivity<SplashViewModel, ActivitySplashBinding>() {


    private val hideHandler = Handler(Looper.myLooper()!!)

    private var isJumpLogin:Boolean = false

    private val hideRunnable = Runnable {
        supportActionBar?.hide()
        if (Build.VERSION.SDK_INT >= 30) {
            mDatabind.fullscreenContent.windowInsetsController?.hide(WindowInsets.Type.statusBars() or WindowInsets.Type.navigationBars())
        } else {
            mDatabind.fullscreenContent.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LOW_PROFILE or
                        View.SYSTEM_UI_FLAG_FULLSCREEN or
                        View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
                        View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
                        View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
                        View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
        }
    }


    override fun initView(savedInstanceState: Bundle?) {
        mDatabind.btJump.setOnClickListener {
            isJumpLogin = true
            LoginActivity.startActivity(this)
            finish()
        }
    }

    override fun createObserver() {
    }

    override fun onPostCreate(savedInstanceState: Bundle?) {
        super.onPostCreate(savedInstanceState)
        delayedHide()
        countDownTimer()
    }

    private fun delayedHide() {
        hideHandler.removeCallbacks(hideRunnable)
        hideHandler.postDelayed(hideRunnable, 100)
    }

    @SuppressLint("SetTextI18n")
    fun countDownTimer(duration: Long = 5) {
        val job = lifecycleScope.launch {
            var timeRemaining = duration
            while (timeRemaining > 0) {
                //点击登录后跳出循环逻辑
                if (isJumpLogin){
                    return@launch
                }
                runOnUiThread {
                    mDatabind.btJump.text = "跳过 $timeRemaining"
                }
                // 执行倒计时操作
                delay(1000)
                timeRemaining -= 1
            }
            // 倒计时结束的操作
            runOnUiThread {
                mDatabind.btJump.text = "跳过 $timeRemaining"
                LoginActivity.startActivity(this@SplashActivity)
                finish()
            }
        }

        job.start()
    }
}